package org.eden.web.controller.blog;

import org.eden.rpc.common.entity.dao.Article;
import org.eden.rpc.common.exception.ConnectException;
import org.eden.rpc.common.service.blog.ArticleService;
import org.eden.rpc.core.client.pooled.DefaultRpcClientPool;
import org.eden.web.pojo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/blog")
public class ArticleController {

    @Autowired
    DefaultRpcClientPool clientPool;

    @GetMapping("/articles")
    @PreAuthorize("hasAnyAuthority('admin', 'guest')")
    public Response articles() {
        try {
            ArticleService service = clientPool.getService(ArticleService.class);
            String articles = service.getArticles();
            clientPool.retrieve();
            return Response.success(articles);
        } catch (ConnectException e) {
            return Response.failed(e.getMessage());
        }
    }

    @PostMapping("/article")
    public Response addArticle(Article article) {
        try {
            ArticleService service = clientPool.getService(ArticleService.class);
            Long id = service.addArticle(article);
            clientPool.retrieve();
            return Response.success(id);
        } catch (ConnectException e) {
            return Response.failed(e.getMessage());
        }
    }

}
